package com.itdaan.portal.business.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bouncycastle.util.encoders.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.itdaan.portal.business.domain.Blog;
import com.itdaan.portal.business.service.BlogService;
import com.itdaan.portal.business.service.CommentService;
import com.itdaan.portal.business.solr.Post;
import com.itdaan.portal.business.solr.SolrClient;
import com.itdaan.portal.business.solr.SolrClient4RICH;
import com.itdaan.portal.common.exception.ViewException;

/**
 * 博客业务控制类
 * @author www.itdaan.com
 */
@Controller
@RequestMapping(value = "/blog")
@SessionAttributes
public class BlogController {

	private Logger logger = LoggerFactory.getLogger(BlogController.class);
	@Resource(name = "blogService")
	private BlogService blogService;
	@Resource(name = "commentService")
	private CommentService commentService;	
	
	@RequestMapping(value = "/{year:\\d+}/{month:\\d+}/{day:\\d+}/{id:\\d+}.html", method = RequestMethod.GET)
    public
    ModelAndView show(
            HttpServletRequest request,
            HttpServletResponse response,
            @PathVariable Integer year,
            @PathVariable String month,
            @PathVariable String day,
            @PathVariable Integer id            
    ) throws ViewException {
		ModelAndView modelAndView = new ModelAndView();
    	try{
    		//第一步：查询博客信息
    		modelAndView.setViewName("portal/blog");
    		Blog blog = blogService.findPostOne(id);
    		//查询内容信息
			SolrClient4RICH.startServer();
			String content = SolrClient4RICH.queryOne(id);
			content = content.replace("<div", "<span").replace("</div>", "</span>").replace("\t", "").replace("\n", "");
			blog.setContent(content);
			modelAndView.addObject("post", blog);
			String base64Author = new String(Base64.encode(blog.getAuthor().getBytes("utf-8")),"utf-8");
			modelAndView.addObject("base64Author", base64Author);
       		//第二步：查找相似的项目信息
    		SolrClient.startServer();
    		List<Post> relateds = SolrClient.getRelated(id+"", 15);
    		modelAndView.addObject("relateds", relateds);
    	}catch(Exception e){
    		e.printStackTrace();
			logger.error("后台业务逻辑出现异常", e);
    	}
    	return modelAndView;
	}
}
